import { Devicesh } from "../Devicesh"
import { MqttUtil } from "../../utils/MqttUtil"
/**
 * 使用mqtt的传感器通信方式
 */
export class MqttDevice implements Devicesh {
  icon: number


  /**
   * 传感器状态
   */
  state: boolean
  /**
   * 设备名称
   */
  deviceName: string

  public topic: string;
  /**
   * comd
   */
  public comd: string = "isOpen";
  /**
   * key
   */
  public key: string = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
  /**
   * 打开指令
   */
  public openValue: string = "1";
  /**
   * 关闭指令
   */
  public closeValue: string = "0";

  /**
   * 发送指令
   */
  command(b: boolean) {
    if (b == this.state) {
      return;
    }
    this.state = b;
    let payload = `{"${this.comd}":${b ? this.openValue : this.closeValue},"key":"${this.key}"}`;
    MqttUtil.publish(this.topic, payload)
  }

  public init(icon: number, deviceName: string, topic: string) {
    this.icon = icon;
    this.deviceName = deviceName;
    this.topic = topic;
    return this;
  }

  public setCmdValue(open: string, close: string) {
    this.openValue = open;
    this.closeValue = close;
    return this;
  }

  public setKey(key: string) {
    this.key = key;
    return this;
  }

  public setCmdKey(cmd: string) {
    this.comd = cmd;
    return this;
  }
}